package com.prs.crm.action.sale;

import java.io.File;
import java.util.Collection;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.action.FlowAction;
import com.prs.crm.annotation.Clew;
import com.prs.crm.annotation.FlowActive;
import com.prs.crm.annotation.FlowStart;
import com.prs.crm.domain.crm.Customer;
import com.prs.crm.domain.flow.WorkFlowProcess;
import com.prs.crm.domain.flow.WorkFlowProcessNode;
import com.prs.crm.domain.sale.SalesContract;
import com.prs.crm.domain.sale.SalesContractDetail;
import com.prs.crm.domain.sale.SalesContractType;
import com.prs.crm.domain.stock.Product;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeInvoice;
import com.prs.crm.service.sale.SalesContractService;
import com.prs.crm.service.sale.SalesContractTypeService;
import com.prs.crm.service.stock.ProductService;
import com.prs.crm.service.sys.CodeInvoiceService;
import com.prs.crm.service.sys.CodeService;

public class SalesContractAction extends FlowAction<SalesContract> {

	private static final long serialVersionUID = 1L;

	private String Encode;

	private CodeInvoice codeInvoice;

	private CodeInvoiceService codeInvoiceService;

	private Code code;

	private CodeService codeService;

	private Collection<CodeInvoice> codelist;

	private SalesContract salesContract;

	private WorkFlowProcess workFlowProcess;

	private Product[] products;

	private String[] pronames;

	private Double[] originalCosts;

	private Double[] nowCosts;

	private Integer[] quotationNums;

	private Double[] rebates;

	private Double[] totalPrices;

	private SalesContractService salesContractService;

	private SalesContractTypeService salesContractTypeService;

	private ProductService productService;

	private PaginationSupport pagination;

	private List<SalesContractType> typelist;

	private List<Product> productlist;

	private Collection<SalesContractDetail> slist;
	private File upload;
	private String uploadFileName;
	private String flow;

	@FlowActive(target = "salesContract", flowservice = "salesContractService")
	@Action("editSalesContract")
	public String editSalesContract() {
		this.typelist = this.getSalesContractTypeService().getAllType();
		this.codelist = this.getCodeInvoiceService()
				.getInvoiceCodeType("销售合同单");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@FlowStart(target = "salesContract", flowservice = "salesContractService")
	@Action(value = "saveSalesContract", results = {
			@Result(name = "success", type = "redirect", location = "listSalesContract"),
			@Result(name = "error", type = "chain", location = "editSalesContract"),
			@Result(name = "none", type = "redirect", location = "listSalesContract") })
	public String saveSalesContract() {

		if ("n".equals(Encode)) {
			int EncodeRplice = this.getCodeService().getBackRpliceAll(
					"手动编码", "销售合同",salesContract.getContractCode());
			if (EncodeRplice != 0) {
				this.addActionError("编码重复!请重新输入");
				return ERROR;
			}
		}
		if("x".equals(Encode)||"".equals(Encode)){
			this.addActionError("请选择编码类型");		
			return ERROR;
		}
		if (flow == null || flow.equals("")) {

			this.addActionError("请添加审核流程");
			return ERROR;
		}
		if (salesContract.getCustomer() == null) {
			this.addActionError("请添加关联客户");
			return ERROR;
		}
		if (salesContract.getContractCode() == null
				|| salesContract.getContractCode().equals("")) {
			this.addActionError("请添加合同编号");
			return ERROR;
		}
		if (salesContract.getContractName() == null
				|| salesContract.getContractName().equals("")) {
			this.addActionError("请添加合同主题");
			return ERROR;
		}
		if (salesContract.getStartDate() == null) {
			this.addActionError("请添加开始时间");
			return ERROR;
		}
		if (salesContract.getOverDate() == null) {
			this.addActionError("请添加终止时间");
			return ERROR;
		}
		if (salesContract.getMyDelegrate() == null) {
			this.addActionError("请添加我方负责人");
			return ERROR;
		}
		if (salesContract.getOtherDelegrate() == null
				|| salesContract.getOtherDelegrate().equals("")) {
			this.addActionError("请添加对方负责人");
			return ERROR;
		}
		if (products == null || nowCosts == null) {
			this.addActionError("请添加产品");
			return ERROR;

		}
		if (salesContract.getContractState() == null) {
			this.addActionError("请选择合同状态");
			return ERROR;
		}


		/**
		 * 编码产生
		 */
		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(salesContract.getContractCode());
		    codes.setCodeMolde("销售合同");
		    codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			this.getCodeService().save(codes);			
			salesContract.setCode(codes);

			this.getSalesContractService().saveSalesContract(salesContract,
					products, pronames, originalCosts, nowCosts, quotationNums,
					rebates, totalPrices, upload, uploadFileName);
		} else {
			CodeInvoice Vob = this.getCodeInvoiceService().getVobject(
					codeInvoice.getId());
			Code codes = new Code();
			codes.setCodeMolde("销售合同");
		    codes.setEntityName(this.getClass().getName());
			codes.setCodeValue(salesContract.getContractCode());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.getCodeInvoiceService().saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			this.getCodeService().save(codes);		
			salesContract.setCode(codes);
			this.getSalesContractService().saveSalesContract(salesContract,
					products, pronames, originalCosts, nowCosts, quotationNums,
					rebates, totalPrices, upload, uploadFileName);
		}

		this.setPrompt("操作成功");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@FlowStart(target = "salesContract", flowservice = "salesContractService")
	@Action(value = "saveUpdateSalesContract", results = {
			@Result(name = "success", type = "redirect", location = "listUpdateSalesContract"),
			@Result(name = "none", type = "redirect", location = "listUpdateSalesContract") })
	public String saveUpdateSalesContract() {
		SalesContract saleObject = this.getSalesContractService()
				.getSalesContract(salesContract.getId());
		saleObject.setContractState(salesContract.getContractState());
		this.getSalesContractService().saveOrUpdate(saleObject);
		this.setPrompt("变更操作成功");
		return SUCCESS;
	}

	@Action(value = "updateSalesContractprocess", results = {
			@Result(name = "success", type = "redirect", location = "listSalesContractProcess"),
			@Result(name = "none", type = "redirect", location = "listSalesContractProcess") })
	public String updateSalesContractprocess() {
		SalesContract SalesContractObject = this.getSalesContractService()
				.getSalesContract(salesContract.getId());
		SalesContractObject.setStartDate(salesContract.getStartDate());
		SalesContractObject.setOverDate(salesContract.getOverDate());
		SalesContractObject.setFlowstatus(1);
		this.getSalesContractService().saveOrUpdate(SalesContractObject);
		for (int z = 0; z < nowCosts.length; z++) {
			SalesContractDetail SalesContractDetailObjec = this
					.getSalesContractService().getSalesContractDetail(
							products[z], salesContract);
			SalesContractDetailObjec.setNowCost(nowCosts[z]);
			SalesContractDetailObjec.setContractNum(quotationNums[z]);
			SalesContractDetailObjec.setRebate(rebates[z]);
			SalesContractDetailObjec.setTotalPrice(totalPrices[z]);
			this.getSalesContractService().saveOrUpdateDetail(
					SalesContractDetailObjec);
		}
		workFlowProcess = SalesContractObject.getProcess();
		WorkFlowProcess workFlowProcessObject = this
				.getWorkflowProcessService().getWorkFlowProcess(
						workFlowProcess.getId());
		workFlowProcessObject.setResult(0);
		workFlowProcessObject.setStatus(1);
		this.getWorkflowProcessService().saveOrUpdate(workFlowProcessObject);
		List<WorkFlowProcessNode> workFlowProcessNodeObjectList = this
				.getWorkflowProcessService().getWorkFlowProcessNode(
						workFlowProcessObject);
		for (int m = 0; m < workFlowProcessNodeObjectList.size(); m++) {
			WorkFlowProcessNode workFlowProcessNodeObject = workFlowProcessNodeObjectList
					.get(m);
			if (m == 0) {
				workFlowProcessNodeObject.setResult(0);
				workFlowProcessNodeObject.setStatus(1);
				this.getWorkflowProcessService()
						.saveOrUpdateWorkFlowProcessNode(
								workFlowProcessNodeObject);
			} else {
				workFlowProcessNodeObject.setResult(0);
				workFlowProcessNodeObject.setStatus(0);
				this.getWorkflowProcessService()
						.saveOrUpdateWorkFlowProcessNode(
								workFlowProcessNodeObject);
			}

		}

		this.setPrompt("变更操作成功");
		return SUCCESS;
	}

	@Action("listSalesContract")
	public String excute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContract.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listSalesContractProcess")
	public String excute2() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContract.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.eq("flowstatus", 3));
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("UpdateSalesContractProcess")
	public String UpdateSalesContractProcess() {
		salesContract = this.getSalesContractService().get(
				salesContract.getId());
		this.slist = salesContract.getDetails();
		this.displayEndNodes(salesContract);
		return SUCCESS;
	}

	@Action("viewSalesContract")
	public String viewSalesContract() {
		salesContract = this.getSalesContractService().get(
				salesContract.getId());
		this.slist = salesContract.getDetails();
		//System.out.println(salesContract.getContractAttach());
		this.displayEndNodes(salesContract);
		return SUCCESS;
	}

	@Action("updateSalesContract")
	public String updateSalesContract() {
		salesContract = this.getSalesContractService().get(
				salesContract.getId());
		this.slist = salesContract.getDetails();
		this.displayEndNodes(salesContract);
		return SUCCESS;
	}

	@Action("listUpdateSalesContract")
	public String excute1() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesContract.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getSalesContractService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

	public SalesContract getSalesContract() {
		return salesContract;
	}

	public void setSalesContract(SalesContract salesContract) {
		this.salesContract = salesContract;
	}

	public SalesContractService getSalesContractService() {
		return salesContractService;
	}

	public void setSalesContractService(
			SalesContractService salesContractService) {
		this.salesContractService = salesContractService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public List<SalesContractType> getTypelist() {
		return typelist;
	}

	public void setTypelist(List<SalesContractType> typelist) {
		this.typelist = typelist;
	}

	public SalesContractTypeService getSalesContractTypeService() {
		return salesContractTypeService;
	}

	public void setSalesContractTypeService(
			SalesContractTypeService salesContractTypeService) {
		this.salesContractTypeService = salesContractTypeService;
	}

	public Product[] getProducts() {
		return products;
	}

	public void setProducts(Product[] products) {
		this.products = products;
	}

	public String[] getPronames() {
		return pronames;
	}

	public void setPronames(String[] pronames) {
		this.pronames = pronames;
	}

	public Double[] getOriginalCosts() {
		return originalCosts;
	}

	public void setOriginalCosts(Double[] originalCosts) {
		this.originalCosts = originalCosts;
	}

	public Double[] getNowCosts() {
		return nowCosts;
	}

	public void setNowCosts(Double[] nowCosts) {
		this.nowCosts = nowCosts;
	}

	public Integer[] getQuotationNums() {
		return quotationNums;
	}

	public void setQuotationNums(Integer[] quotationNums) {
		this.quotationNums = quotationNums;
	}

	public Double[] getRebates() {
		return rebates;
	}

	public void setRebates(Double[] rebates) {
		this.rebates = rebates;
	}

	public Double[] getTotalPrices() {
		return totalPrices;
	}

	public void setTotalPrices(Double[] totalPrices) {
		this.totalPrices = totalPrices;
	}

	public Collection<SalesContractDetail> getSlist() {
		return slist;
	}

	public void setSlist(Collection<SalesContractDetail> slist) {
		this.slist = slist;
	}

	public WorkFlowProcess getWorkFlowProcess() {
		return workFlowProcess;
	}

	public void setWorkFlowProcess(WorkFlowProcess workFlowProcess) {
		this.workFlowProcess = workFlowProcess;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public List<Product> getProductlist() {
		return productlist;
	}

	public void setProductlist(List<Product> productlist) {
		this.productlist = productlist;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getFlow() {
		return flow;
	}

	public void setFlow(String flow) {
		this.flow = flow;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public CodeInvoice getCodeInvoice() {
		return codeInvoice;
	}

	public void setCodeInvoice(CodeInvoice codeInvoice) {
		this.codeInvoice = codeInvoice;
	}

	public CodeInvoiceService getCodeInvoiceService() {
		return codeInvoiceService;
	}

	public void setCodeInvoiceService(CodeInvoiceService codeInvoiceService) {
		this.codeInvoiceService = codeInvoiceService;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeInvoice> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeInvoice> codelist) {
		this.codelist = codelist;
	}

}
